/* eslint-disable no-async-promise-executor */
const { verify } = require('../models/tokenFn')
const model = require("../models/model")
const { getFile } = require('../models/getfile')
const { Op } = require("sequelize")

exports.myGoodsList = async (ctx) => {
  const userId = verify(ctx.header)
  const MyGoods = model.goodsdetails.MyGoods //获取模型
  const { categoryTwoId, page, size, value } = ctx.request.body
  if (!page || !size) {
    ctx.fail('参数错误')
    return
  }
  function allFn() {
    return new Promise(async(resolve) => {
      const where = {
        parentId: categoryTwoId ? categoryTwoId : undefined,
        adminId: userId,
        name: {
          [Op.like]: `%${value || ''}%`
        }
      }
      for (const prop in where) {
        if (!where[prop]) {
          delete where[prop]
        }
      }
      const count_res = await MyGoods.findAndCountAll({
        order: [
          ['updateTime', 'DESC'],
        ],
        where,
        offset: (page-1) * size,
        limit: size
      })
      if (count_res.rows !== undefined && count_res.rows.length > 0) {
        // 获取图片地址
        const iconId = new Promise(async(resolve) => { // 获取icon图标
          let flag = 0
          for (let i = 0; i < count_res.rows.length; i++) {
            getFile(count_res.rows[i].iconId).then(res => {
              flag++
              count_res.rows[i].iconId = res
              if (flag === count_res.rows.length) {
                resolve('success')
              }
            })
          }
        })
        const homeImageIds = new Promise(async(resolve) => { // 获取轮播图
          let flag = 0
          for (let i = 0; i < count_res.rows.length; i++) {
            getFile(count_res.rows[i].homeImageIds).then(res => {
              flag++
              count_res.rows[i].homeImageIds = res
              if (flag === count_res.rows.length) {
                resolve('success')
              }
            })
          }
        })
        const detailsImageIds = new Promise(async(resolve) => { // 获取轮播图
          let flag = 0
          for (let i = 0; i < count_res.rows.length; i++) {
            getFile(count_res.rows[i].detailsImageIds).then(res => {
              flag++
              count_res.rows[i].detailsImageIds = res
              if (flag === count_res.rows.length) {
                resolve('success')
              }
            })
          }
        })
        // 执行全部文件异步后再返回
        let fileAll = await Promise.all([iconId, homeImageIds, detailsImageIds])
        if (fileAll) {
          resolve(count_res)
        }
      } else {
        resolve(count_res)
      }
    })
  }
  const res = await allFn()
  if (res) {
    ctx.success({
      total: res.count, // 总页数
      pageNum: Math.trunc((res.count + (size -1) )/size), // 分页数量
      page: parseInt(page), // 页码
      size: parseInt(size), // 页数
      list: res.rows
    })
  }
}

exports.myGoodsDetail = async (ctx) => {
  const userId = verify(ctx.header)
  const { goodsId } = ctx.request.body

  const MyGoods = model.goodsdetails.MyGoods //获取模型
  const CategoryTwo = model.categoryTwo.CategoryTwo
  const MyGoodsList = model.goodsdetailsList.MyGoodsList
  const MyGoodsListSku = model.goodsdetailsSku.MyGoodsListSku
  const MyGoodsListType = model.goodsdetailsType.MyGoodsListType

  if (!goodsId) {
    ctx.fail('参数错误')
    return
  }
  function skuPromise(skus) {
    return new Promise(async(resolve) => {
      const skuList = skus.split(',').filter(item => item !== '')
      if (skuList.length > 0) {
        //  先查询 规格类目
        const skuListPromise = skuList.map(it => MyGoodsListSku.findOne({ where: { k_s: it } }))
        const skuListPromiseAll = await Promise.all(skuListPromise)
        console.log(skuListPromiseAll, '主规格')
        if (skuListPromiseAll.length > 0) {
          // 再查询 规格类目下的具体子项 规格值
          const TypePromise = skuListPromiseAll.map(it => MyGoodsListType.findAll({ where: { skuId: it.id, parentId: goodsId } }))
          const TypePromiseAll = await Promise.all(TypePromise)
          console.log(TypePromiseAll, '副规个')
          if (TypePromiseAll.length > 0) {
            let vData = []
            TypePromiseAll.forEach(item => { // Promise.all生成了多个数组 进行拆解（把所有对象集合到一个数组里）
              if (Array.isArray(item)) { // 如果子集为数组继续循环
                item.forEach(it => {
                  if (Array.isArray(it)) {
                    it.forEach(v => {
                      vData.push(v) // 最多2级
                    })
                  } else {
                    vData.push(it)
                  }
                })
              } else {
                vData.push(item)
              }
            })
            const imgUrl = new Promise(async(resolve) => { // 获取规格类目图片，只有第一个规格类目可以定义图片
              let flag = 0
              if (vData.length > 0) {
                for (let i = 0; i < vData.length; i++) {
                  getFile(vData[i].imgUrl).then(res => {
                    flag++
                    vData[i].imgUrl = res
                    if (flag === vData.length) {
                      resolve('success')
                    }
                  })
                }
              } else {
                resolve('success')
              }
            })
            const previewImgUrl = new Promise(async(resolve) => { // 获取用于预览显示的规格类目图片
              let flag = 0
              if (vData.length > 0) {
                for (let i = 0; i < vData.length; i++) {
                  getFile(vData[i].previewImgUrl).then(res => {
                    flag++
                    vData[i].previewImgUrl = res
                    if (flag === vData.length) {
                      resolve('success')
                    }
                  })
                }
              } else {
                resolve('success')
              }
            })
            // 执行全部文件地址异步后再返回
            let fileAll = await Promise.all([imgUrl, previewImgUrl])
            if (fileAll) { // 获取图片地址后再返回
              // 合并数据
              skuListPromiseAll.forEach(item => {
                item.largeImageMode = item.largeImageMode != 0
                item['v'] = []
                vData.forEach(v => {
                  if (item.id == v.skuId) {
                    item['v'].push(v)
                  }
                })
              })
              resolve(skuListPromiseAll)
            }
          } else {
            resolve([])
          }
        } else {
          resolve([])
        }
      } else {
        resolve([])
      }
    })
  }
  // 查询 所有 sku 的组合列表，比如红色、M 码为一个 sku 组合，红色、S 码为另一个组合
  function listPromise() {
    return new Promise(async(resolve) => {
      const res = await MyGoodsList.findAll({
        where: {
          parentId: goodsId
        }
      })
      if (res !== undefined && res.length > 0) {
        res.forEach(item => {
          for (const prop in item) {
            if (item[prop] == null) {
              delete item[prop]
            }
          }
        })
        resolve(res)
      } else {
        resolve([])
      }
    })
  }
  function allFn() {
    return new Promise(async(resolve) => {
      const goods_res = await MyGoods.findOne({
        where: {
          adminId: userId,
          id: goodsId
        }
      })
      if (goods_res) {
        goods_res.none_sku = goods_res.none_sku === 1
        // 获取图片地址
        const iconId = new Promise(async(resolve) => { // 获取icon图标
          if (goods_res.iconId) {
            const res = await getFile(goods_res.iconId)
            if (res) {
              goods_res.iconId = res
              resolve('success')
            }
          }
        })
        const homeImageIds = new Promise(async(resolve) => { // 获取轮播图
          if (goods_res.homeImageIds) {
            const res = await getFile(goods_res.homeImageIds)
            if (res) {
              goods_res.homeImageIds = res
              resolve('success')
            }
          }
        })
        const detailsImageIds = new Promise(async(resolve) => { // 获取轮播图
          if (goods_res.detailsImageIds) {
            const res = await getFile(goods_res.detailsImageIds)
            if (res) {
              goods_res.detailsImageIds = res
              resolve('success')
            }
          }
        })
        const fatherId = new Promise(async(resolve) => { // 获取商品一类分类id
          const res = await CategoryTwo.findOne({ where: { id: goods_res.parentId }})
          goods_res['fatherId'] = res.parentId || ''
          resolve('success')
        })
        // 执行获取全部文件异步后再返回
        const fileAll = await Promise.all([iconId, homeImageIds, detailsImageIds, fatherId])
        if (fileAll) {
          if (goods_res.sku) { // 表示该为有规格类目
            const goodsAll = await Promise.all([skuPromise(goods_res.sku), listPromise()])
            goods_res['skuList'] = goodsAll[0]
            goods_res['list'] = goodsAll[1]
            resolve(goods_res)
          } else {
            goods_res['skuList'] = []
            goods_res['list'] = []
            resolve(goods_res)
          }
        }
      } else {
        resolve()
      }
    })
  }
  const res = await allFn()
  if (res) {
    ctx.success(res)
  } else {
    ctx.fail('查询失败')
  }
}

exports.myGoodsModify = async(ctx) => {
  const userId = verify(ctx.header)
  const MyGoods = model.goodsdetails.MyGoods //获取模型
  if (!ctx.request.body) {
    ctx.fail('参数错误')
    return
  }
  function addMyGoods() {
    return new Promise(async(resolve) => {
      const data = Object.assign(ctx.request.body, { adminId: userId})
      const res = await MyGoods.create(data)
      if (res) {
        resolve({
          data: res,
          msg: '发布成功',
          code: 0
        })
      } else {
        resolve({
          msg: '发布失败',
          code: -1
        })
      }
    })
  }
  function modifyMyGoods() {
    return new Promise(async(resolve) => {
      if (!ctx.request.body.id) {
        resolve({
          msg: '参数错误',
          code: -1
        })
        return
      }
      const res = await MyGoods.update(ctx.request.body, {
        where: {
          id: ctx.request.body.id
        }
      })
      if (res[0] ===1) {
        resolve({
          data: { id: ctx.request.body.id },
          msg: '修改成功',
          code: 0
        })
      } else {
        resolve({
          msg: '修改失败',
          code: 0
        })
      }
    })
  }
  let res
  if (!ctx.request.body.id) {
    res =  await addMyGoods()
  } else {
    res = await modifyMyGoods()
  }
  if (res.code === 0) {
    ctx.success(res.data || '', res.msg)
  } else {
    ctx.fail(res.msg)
  }
}
